﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using qltscd.Models;
using qltscd.Models.ScreenClient;
using qltscd.Contansts;
using Telerik.Web.Mvc;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.IO;
using qltscd.Helper;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web.Routing;


namespace qltscd.Controllers
{
    public class DanhMucHangSanXuatController : BaseController {
        protected override void OnActionExecuting (ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);
            if (SessionHelper.QuyenNhom[qltscd.Contansts.KeyContansts.QuyenDanhMuc] == '0') {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
                    controller = "KhongCoQuyen",
                    action = "Index"
                }));
            }
        }
        #region Properties Section
        private QLTBEntities db = new QLTBEntities();
        #endregion

        #region Views Section
        public ActionResult Index()
        {
            Session[SessionConstants.ERROR_MESSAGE] = string.Empty;
            DanhMucHangSanXuatScreenClient screen = new DanhMucHangSanXuatScreenClient();
            if (Session[SessionScreenContansts.DanhMucHangSanXuat_SCREENCLIENT] != null) {
                screen = (DanhMucHangSanXuatScreenClient)Session[SessionScreenContansts.DanhMucHangSanXuat_SCREENCLIENT];
            }
            Search(screen);
            return View(screen);
        }

        [HttpPost]
        public ActionResult Index (DanhMucHangSanXuatScreenClient screen) {
            Search(screen);
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index () {
            DanhMucHangSanXuatScreenClient screen = new DanhMucHangSanXuatScreenClient();
            if (Session[SessionScreenContansts.DanhMucHangSanXuat_SCREENCLIENT] != null) {
                screen = (DanhMucHangSanXuatScreenClient)Session[SessionScreenContansts.DanhMucHangSanXuat_SCREENCLIENT];
            }
            Search(screen);
            return View(new GridModel(screen.DanhMucHangSanXuats));
        }
        public ActionResult Create()
        {
            Models.BaseClient.DanhMucHangSanXuat hsx = new Models.BaseClient.DanhMucHangSanXuat() { IdentityHangSanXuat = -1 };
            return View(hsx);
        }

        public ActionResult SuaHangSanXuat()
        {
            string id = Request.QueryString["id"];
            if (id != null)
            {
                int iden = Convert.ToInt32(id);
                DanhMucHangSanXuat hsx = db.DanhMucHangSanXuats.Single(i => i.IdentityHangSanXuat == iden);
                Models.BaseClient.DanhMucHangSanXuat hsxC = new Models.BaseClient.DanhMucHangSanXuat();
                ObjectHelper.Copy(hsx, hsxC);
                return View(hsxC);

            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult ShowPdf()
        {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucHangSanXuat.rpt";
            rpt.SetDatabaseLogon("sa", "sa");
            rpt.Load();
            //rpt.SetDataSource(db.DanhMucHangSanXuats);
            Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }

        public FileResult ExportToExcel()
        {

            DataTable myTable = new DataTable();

            var data = from n in db.DanhMucHangSanXuats
                       select n;

            myTable.Columns.Add("Mã Hãng Sản Xuất");
            myTable.Columns.Add("Tên Hãng Sản Xuất");
            myTable.Columns.Add("Trang Web");

            foreach (var n in data)
            {
                myTable.Rows.Add(n.MaHangSanXuat.ToString(), n.TenHangSanXuat.ToString(), n.TrangWeb.ToString());
            }

            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + "BaoCaoDanhMucHangSanXuat.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("DANH MỤC HÃNG SẢN XUẤT\t\t\t\n\n");
                for (int count = 0; count < myTable.Columns.Count; count++)
                {
                    if (myTable.Columns[count].ColumnName != null)
                        sb.Append(myTable.Columns[count].ColumnName);
                    if (count < myTable.Columns.Count - 1)
                        sb.Append("\t");
                }

                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                int soDem = 0;
                while (myTable.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();
                    for (int col = 0; col < myTable.Columns.Count - 1; col++)
                    {
                        if (myTable.Rows[soDem][col] != null)
                            sb.Append(myTable.Rows[soDem][col].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    if (myTable.Rows[soDem][myTable.Columns.Count - 1] != null)
                        sb.Append(myTable.Rows[soDem][myTable.Columns.Count - 1].ToString().Replace(",", " "));
                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }      
            }
            catch
            { 
                
            }

            myTable.Dispose();
            Response.End();
            return File("BaoCaoDanhMucHangSanXuat", "application/ms-excel", "BaoCaoDanhMucHangSanXuat.xls");
        }


        public ActionResult ThongTinHangSanXuat(int id)
        {
            DanhMucHangSanXuat hsx = db.DanhMucHangSanXuats.Single(i => i.IdentityHangSanXuat == id);
            return View(hsx);
        }
        #endregion 
        
        #region CRUD Section
        [HttpPost]
        public ActionResult SuaHangSanXuat(Models.BaseClient.DanhMucHangSanXuat hsxC)
        {
            if (ModelState.IsValid)
            {
                //code de luu lai
                DanhMucHangSanXuat h = db.DanhMucHangSanXuats.Single(i => i.IdentityHangSanXuat == hsxC.IdentityHangSanXuat);
                if (hsxC.MaHangSanXuat != h.MaHangSanXuat) {
                    if (db.DanhMucHangSanXuats.Count(i => i.MaHangSanXuat == hsxC.MaHangSanXuat) > 0) {
                        ViewData[SessionConstants.ERROR_MESSAGE] = "Mã hãng sản xuất " + hsxC.MaHangSanXuat + " đã tồn tại";
                        return View(hsxC);
                    }
                }
                ObjectHelper.Copy(hsxC, h);
                db.ObjectStateManager.ChangeObjectState(h, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(hsxC);
        }
       
        [HttpPost]
        public ActionResult Create(Models.BaseClient.DanhMucHangSanXuat danhmuchangsanxuat)
        {
            if (ModelState.IsValid)
            {
                if (db.DanhMucHangSanXuats.Count(o => o.MaHangSanXuat == danhmuchangsanxuat.MaHangSanXuat) > 0) {
                    ViewData[SessionConstants.ERROR_MESSAGE] = "Mã hãng sản xuất " + danhmuchangsanxuat.MaHangSanXuat + " đã tồn tại";
                    return View(danhmuchangsanxuat);
                }
                DanhMucHangSanXuat hsx = new DanhMucHangSanXuat();
                ObjectHelper.Copy(danhmuchangsanxuat, hsx);
                db.DanhMucHangSanXuats.AddObject(hsx);
                db.SaveChanges();
                return RedirectToAction("Create");
            }
            return View(danhmuchangsanxuat);
        }
        public ActionResult Delete(int id)
        {
            DanhMucHangSanXuat hsx = db.DanhMucHangSanXuats.Single(i => i.IdentityHangSanXuat == id);
            db.DanhMucHangSanXuats.DeleteObject(hsx);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult XoaHangSanXuat()
        {
            string id = Request.QueryString["id"];
            try
            {
                if (id != null)
                {
                    int iden = Convert.ToInt32(id);
                    DanhMucHangSanXuat hsx = db.DanhMucHangSanXuats.Single(i => i.IdentityHangSanXuat == iden);
                    db.DanhMucHangSanXuats.DeleteObject(hsx);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
        #endregion

        #region Helper Section
        private void Search (DanhMucHangSanXuatScreenClient screen) {
            if (screen == null) { screen = new DanhMucHangSanXuatScreenClient(); }
            var list = db.DanhMucHangSanXuats.OrderBy(i => i.TenHangSanXuat);
            screen.DanhMucHangSanXuats.Clear();
            foreach (DanhMucHangSanXuat hang in list) {
                qltscd.Models.BaseClient.DanhMucHangSanXuat hangClient = new Models.BaseClient.DanhMucHangSanXuat();
                ObjectHelper.Copy(hang, hangClient);
                screen.DanhMucHangSanXuats.Add(hangClient);
            }
            Session[SessionScreenContansts.DanhMucHangSanXuat_SCREENCLIENT] = screen;
        }
        #endregion

        public void clearFolder()
        {
            DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/") + "//Reports");

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.Delete();
            }

            //foreach (DirectoryInfo di in dir.GetDirectories())
            //{
            //    clearFolder(di.FullName);
            //    di.Delete();
            //}
        }

       
    }
}
